package edu.umb.cs.antmanager.client;

import java.io.File;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.XmlLogger;

import edu.umb.cs.antmanager.domain.PropertyType;
import edu.umb.cs.antmanager.domain.TestType;
import static edu.umb.cs.antmanager.common.Constants.*;

public class AntRunner implements Runnable {
	private TestType test;
	private RMIAgentServer server;

	public AntRunner(TestType test, RMIAgentServer server) {
		this.test = test;
		this.server = server;
	}

	public AntRunner(TestType test) {
		this(test, null);
	}

	@Override
	public void run() {
		File buildFile = new File(ANT_MANAGER_HOME+"\\"+test.getFile());
		Project p = new Project();
		p.setUserProperty("ant.file", buildFile.getAbsolutePath());

		// add by zexu for XML logging
		p.setUserProperty("XmlLogger.file", ANT_MANAGER_HOME+"\\"+test.getName() + ".xml");
		p.setUserProperty("ant.XmlLogger.stylesheet.uri", "");
		XmlLogger xmlLogger = new XmlLogger();
		xmlLogger.setMessageOutputLevel(Project.MSG_INFO);
		p.addBuildListener(xmlLogger);

		/*
		 * DefaultLogger consoleLogger = new DefaultLogger();
		 * consoleLogger.setErrorPrintStream(System.err);
		 * consoleLogger.setOutputPrintStream(System.out);
		 * consoleLogger.setMessageOutputLevel(Project.MSG_VERBOSE);
		 * p.addBuildListener(consoleLogger);
		 */

		try {
			p.fireBuildStarted();
			p.init();
			ProjectHelper helper = ProjectHelper.getProjectHelper();
			p.addReference("ant.projectHelper", helper);
			helper.parse(p, buildFile);
			for (PropertyType prop : test.getPropertyArray()) {
				p.setProperty(prop.getName(), prop.getValue());
			}
			p.executeTarget(test.getTarget());
			p.fireBuildFinished(null);
		} catch (BuildException e) {
			p.fireBuildFinished(e);
		} finally {
			if (server != null)
				server.freeServer();
		}
	}
}
